#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <strings.h>
#include <string.h>
#include <error.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

using namespace LogMudule;
using namespace ThreadPoolModule;

const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1"; //表示本地主机
const static uint16_t gdefaultport = 8080;

using adduser_t = std::function<void(InetAddr &)>;
using remove_t = std::function<void(InetAddr &)>;
using task_t = std::function<void()>;
using route_t = std::function<void(int sockfd, const std::string &message)>;

class UdpServer
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _sockfd(gsockfd), _addr(port), _isrunning(false)
    {
    }

    void RegisterService(adduser_t adduser, route_t route,remove_t deluser)
    {
        _adduser = adduser;
        _route = route;
        _deluser = deluser;
    }

    void InitServer()
    {
        // 1. 创建Socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, socket is : " << _sockfd;

        // 2.把socket设置进入内核 bind
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            // 1.接受数据
            char inbuffer[1024]; // string
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, CONV(&peer), &len);
            char *p = inbuffer;
            
            // 执行成功
            if (n > 0)
            {
                // 2.发数据
                // 2.1获取客户端socket
                InetAddr client(peer);
                inbuffer[n] = 0;
                std::string message;
                if (strcmp(inbuffer, "QUIT") == 0)
                {
                    // 移除用户
                    _deluser(client);
                    message  = client.Addr() + "# " + "溜了溜了";

                }
                else
                {
                    // 2.2 新增用户
                    _adduser(client);
                    message = client.Addr() + "# " + inbuffer; 
                }
                


                // 2.3 构建转发任务，把任务推送给线程池，让线程池进行转发
                task_t task = std::bind(UdpServer::_route, _sockfd, message);
                ThreadPool<task_t>::getInstance()->Equeue(task);


                // 2.4 发送数据
                // std::string clentinfo = client.Ip() + ":" +std::to_string(client.Port())+" # " + inbuffer;
                // LOG(LogLevel::DEBUG) <<clentinfo;
                // std::string echo_string = "echo# ";
                // echo_string += inbuffer;
                // ::sendto(_sockfd,message.c_str(),message.size(),0,CONV(&peer),sizeof(peer));
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

private:
    int _sockfd;
    InetAddr _addr;
    bool _isrunning; // 表示服务器

    // 新增用户
    adduser_t _adduser;
    // 移除用户
    remove_t _deluser;
    // 路由转发
    route_t _route; // _route是回调
};

#endif